<?php

require_once dirname(__FILE__).'/../lib/carGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/carGeneratorHelper.class.php';

/**
 * tree actions.
 *
 * @package    NestedAdmin
 * @subpackage tree
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12474 2008-10-31 10:41:27Z fabien $
 */
class carActions extends autoCarActions {

	protected function addSortCriteria($criteria) {
		$criteria->addAscendingOrderByColumn(CarPeer::SCOPE); // config
		$criteria->addAscendingOrderByColumn(CarPeer::TREE_LEFT);
	}

	public function executeBatch(sfWebRequest $request) {
		if ("batchOrder" == $request->getParameter('batch_action')) {
			return $this->executeBatchOrder($request);
		}
		parent::executeBatch($request);
	}

	public function executeBatchOrder(sfWebRequest $request) {
		$newparent = $request->getParameter('newparent');

		$ids = array();
		foreach ($newparent as $key => $val) {
			$ids[$key] = true;
			if (!empty($val)) {
				$ids[$val] = true;
			}
		}
		$ids = array_keys($ids);

		//validate if all id's exist
		$validator = new sfValidatorPropelChoiceMany(array('model' => 'Car'));
		try {
			// validate ids
			$ids = $validator->clean($ids);

			// the id's validate, now update the tree
			$count = 0;
			$flash = "";

			foreach ($newparent as $id => $parentId){
				if (!empty($parentId)){
					$node = CarPeer::retrieveByPK($id);
					$parent = CarPeer::retrieveByPK($parentId);

					if (!$parent->isDescendantOfOrEqualTo($node)) {
						$node->moveToFirstChildOf($parent);
						$node->save();
						$count++;
						$flash .= "<br/>Moved '".$node->getName()."' under '".$parent->getName()."'.";
					}
				}
			}
			if ($count > 0) {
				$this->getUser()->setFlash('notice', sprintf("Tree order updated, moved %s item%s:".$flash, $count, ($count > 1 ? 's' : '')));
			}
			else {
				$this->getUser()->setFlash('error', "You must at least move one item to update the tree order");
			}
		}
		catch (sfValidatorError $e) {
			$this->getUser()->setFlash('error', 'Cannot update the tree order, maybe some item are deleted, try again');
		}
		$this->redirect('@car');
	}

	public function executeListNew(sfWebRequest $request) {
		$this->executeNew($request);
		$this->form->setDefault('parent_id', $request->getParameter('id'));
		$this->setTemplate('edit');
	}
}
